package com.example.partyplaner;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

public class DatabaseConnection extends AsyncTask<String, String, WebserviceResponse> {
	public AsyncResponse delegate=null;
	private Activity callingActivity;

	public DatabaseConnection(Activity callingActivity) {
		this.callingActivity = callingActivity;
	}
	
	
	protected void onPreExecute() {
		callingActivity.showDialog(MainActivity.PLEASE_WAIT_DIALOG);
	}

	
	protected WebserviceResponse doInBackground(String... params) {
		try {
			if (params[1].equals("GET"))
				return sendGet(params[0], params[2]);
			else if (params[1].equals("POST"))
				return sendPost(params[0], params[2]);
		} catch (IOException | JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	protected void onPostExecute(WebserviceResponse result) {
		if (result==null)
		{
			Toast.makeText(callingActivity, "Cannot connect with webservice!", Toast.LENGTH_SHORT).show();
		}
		else{
			Toast.makeText(callingActivity, "Result found!", Toast.LENGTH_SHORT).show();
		}		
		callingActivity.removeDialog(MainActivity.PLEASE_WAIT_DIALOG);
		delegate.processFinish(result);
	}

	public WebserviceResponse sendPost(String address, String json) throws IOException, JSONException {
		URL url = new URL(address);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setInstanceFollowRedirects(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/json");
		conn.setRequestProperty("charset", "utf-8");
		conn.setUseCaches(false);
		DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
		dos.writeBytes(json.toString());
		dos.flush();
		dos.close();

		int responseCode = conn.getResponseCode();
		String responseMsg = "";
		WebserviceResponse response=null;
		if (conn.getInputStream() != null)
		{
			responseMsg = convertInputStreamToString(conn.getInputStream());
			response=new WebserviceResponse();
			response.setResponseMsg(responseMsg);
			response.setResponseCode(responseCode);
		}
		Log.i("PartyPlanner", responseMsg);
		Log.i("PartyPlanner", "Code:" + responseCode);
			
		conn.disconnect();
		
		return response;
	}

	
	public WebserviceResponse sendGet(String addres, String params) throws IOException,JSONException {
		URL url = new URL(addres + "/" + params);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");

		int responseCode = conn.getResponseCode();
		String responseMsg = "";
		WebserviceResponse response=null;
		if (conn.getInputStream() != null){
			responseMsg = convertInputStreamToString(conn.getInputStream());
			response=new WebserviceResponse();
			response.setResponseMsg(responseMsg);
			response.setResponseCode(responseCode);
			conn.disconnect();
		}
		Log.i("PartyPlanner", responseMsg);
		Log.i("PartyPlanner", "Code:" + responseCode);
		
		return response;
	}

	
	private static String convertInputStreamToString(InputStream inputStream) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
		String line = "";
		String result = "";
		while ((line = bufferedReader.readLine()) != null)
			result += line;

		inputStream.close();
		
		return result;	
	}
	
}
